package edu.hubu.shop9.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.hubu.shop9.exception.MyException;
import edu.hubu.shop9.common.JsonResult;
import edu.hubu.shop9.entity.Employee;
import edu.hubu.shop9.query.EmployeeQuery;
import edu.hubu.shop9.service.IDepartmentService;
import edu.hubu.shop9.service.IEmployeeService;
import edu.hubu.shop9.util.FileUtils;
import edu.hubu.shop9.util.ObjectUtils;
import edu.hubu.shop9.vo.EmployeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author waxijiang
 * @since 2021-07-26
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    IEmployeeService employeeService;

    @Autowired
    IDepartmentService departmentService;

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "test";
    }

    @RequestMapping("/selectAll")
    public String selectAll1(Model model) {
        List<Employee> list = employeeService.list();
        model.addAttribute("list", list);
        return "employee/employeeList";
    }

    @RequestMapping("/page")
    @ResponseBody
    public Map<String, Object> selectAll(EmployeeQuery query, int page, int rows) {
        Page<EmployeeVo> page1 = new Page<>(page, rows);

        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        Map<String, Object> fields = ObjectUtils.getNotNullFields(query);
        // 构造like条件
        for (Map.Entry<String, Object> entry : fields.entrySet()) {
            if (!"".equals(entry.getValue())) {
                if (entry.getValue() instanceof String) {
                    wrapper.like(entry.getKey(), entry.getValue());
                } else if (entry.getValue() instanceof Long || entry.getValue() instanceof Integer) {
                    wrapper.eq(entry.getKey(), entry.getValue());
                }
            }
        }

        IPage<EmployeeVo> pageInfo = employeeService.selectByQuery(wrapper, page1);
        // 使用map传递到前台
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("rows", pageInfo.getRecords());
        return resultMap;
    }


    @RequestMapping("/deleteByKey")
    @ResponseBody
    public JsonResult deleteByKey(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.removeById(id);
            jsonResult.setMsg("已经删掉了");
        } catch (Exception e) {
            e.printStackTrace();
        }
//		使用map传递到前台
        return jsonResult;
    }


    @RequestMapping("/checkUsername")
    @ResponseBody
    public Boolean checkUsername(Long id, String username) {
//		1.如何id有，代表代表是一个修改的操作
        if (id != null) {
//			2.再根据这个id查询出employee
            Employee emp = employeeService.getById(id);
//			3.再跟传递过来的username进行对比
            if (username.equals(emp.getUsername())) {
                return true;
            }
        }
        return employeeService.checkUsername(username);
    }


    @RequestMapping("/save")
    @ResponseBody
    public JsonResult save(Employee employee, MultipartFile file) throws FileNotFoundException {
        employee.setHeadimage(FileUtils.fileSave(file, "/images/head"));
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.save(employee);
            jsonResult.setMsg("添加成功");
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @RequestMapping("/update")
    @ResponseBody
    public JsonResult update(Employee employee, MultipartFile file) throws FileNotFoundException {
        if (file != null) {
            employee.setHeadimage(FileUtils.fileSave(file, "/images/head"));
        }
        System.out.println("===========================employee:" + employee);
        JsonResult jsonResult = new JsonResult();
        try {
            employeeService.updateById(employee);
            jsonResult.setMsg("修改成功");
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @RequestMapping("/import")
    @ResponseBody
    public JsonResult importData(@RequestParam("file") MultipartFile file) {
        JsonResult jsonResult = new JsonResult();
        String fileName = file.getOriginalFilename();
        try {
            if (employeeService.batchImport(fileName, file)) {
                return new JsonResult();
            }
        } catch (MyException | IOException e) {
            e.printStackTrace();
            jsonResult.setMsg(e.getMessage());
        }
        jsonResult.setSuccess(false);
        return jsonResult;
    }
}

